package com.ebupt.migu.common.util;

import cn.hutool.core.util.StrUtil;
import com.ebupt.migu.common.pojo.CustomerFileBean;

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tz
 */
public class SignUtils {

    public static <T> String getStr(T t, String secretId, String requestRefId) throws IllegalAccessException {
        Map<String, String> map = new HashMap<>();
        map.put("requestRefId", requestRefId);
        map.put("secretId", secretId);
        if (t != null){
            for (Field field : t.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object obj = field.get(t);
                if(null != obj){
                    if (obj instanceof CustomerFileBean) {
                        map.put(fieldName, getStrByCustomerFile(obj));
                    } else {
                        map.put(fieldName, obj.toString());
                    }
                }
            }
        }
        List<String> collect = map.keySet().stream().sorted(Comparator.<String>naturalOrder()).collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        for (String k : collect) {
            sb.append(k).append("=").append(map.get(k)).append("&");
        }
        return StrUtil.sub(sb.toString(), 0, -1);
    }

    private static String getStrByCustomerFile(Object obj) throws IllegalAccessException {
        Map<String, String> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object valObj = field.get(obj);
            if(null != valObj){
                map.put(fieldName, valObj.toString());
            }
        }
        List<String> collect = map.keySet().stream().sorted(Comparator.<String>naturalOrder()).collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        for (String k : collect) {
            sb.append(map.get(k)).append("_");
        }
        return StrUtil.sub(sb.toString(), 0, -1);
    }

}
